import {
  addQuestionType,
  deleteQuestionType,
  getQuestionTypeList,
  removeRule,
  updateQuestionType
} from '@/services/ant-design-pro/api';
import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormDigit,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, Drawer, Form, message} from 'antd';
import React, {useEffect, useRef, useState} from 'react';

/**
 * @en-US Add node
 * @zh-CN 添加题型
 * @param fields
 */
const handleAdd = async (fields: API.QuestionTypeAddParams) => {
  const hide = message.loading('正在添加');
  try {
    const res = await addQuestionType({
      ...fields,
    });
    hide();
    if (res.code === 200 && res.data?.questionTypeId > 0) {
      message.success('新增题型成功！');
      return true;
    } else {
      hide();
      message.error('新增题型失败！请重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('新增题型失败！请重试');
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新题型
 *
 * @param fields
 */
const handleUpdate = async (fields: API.QuestionTypeUpdateParams) => {
  const hide = message.loading('正在修改');
  try {
    const res = await updateQuestionType({
      ...fields
    });
    if (res.code === 200 && res.data?.questionTypeId > 0) {
      hide();
      message.success('修改题型成功!');
      return true;
    } else {
      hide();
      message.error('修改题型失败!请重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('修改题型失败!请重试');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除题型
 *
 * @param
 */
const handleDelete = async (value: number) => {
  const hide = message.loading('正在删除');
  try {
    const res = await deleteQuestionType({
      questionTypeId: value
    });
    if (res.code === 200 && res.data?.questionTypeId > 0) {
      hide();
      message.success('删除成功!');
      return true;
    } else {
      hide();
      message.error('删除失败!请重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败!请重试');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 批量删除题型
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.RuleListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeRule({
      key: selectedRows.map((row) => row.key),
    });
    hide();
    message.success('Deleted successfully and will refresh soon');
    return true;
  } catch (error) {
    hide();
    message.error('Delete failed, please try again');
    return false;
  }
};
const QuestionTypeTableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();
  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);
  const [data, setData] = useState<API.QuestionType[]>()
  const [updateForm] = Form.useForm()


  // 初始化数据
  const initData = async () => {
    let res = await getQuestionTypeList();
    if (res.code === 200) {
      setData(res.data)
    }
  }

  // 初始化生命周期函数
  useEffect(() => {
    initData()
  }, [])

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns: ProColumns<API.QuestionType>[] = [
    {
      title: '题型 ID',
      dataIndex: 'id',
      tip: 'The Question Type ID is the unique key',
    },
    {
      title: '题型名称',
      dataIndex: 'questionName',
      valueType: 'textarea',
    },
    {
      title: '题型分数',
      dataIndex: 'questionScore',
      sorter: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <Button variant="solid" color="cyan" key={"edit"} onClick={() => {
          // 设置当前行值
          updateForm.setFieldValue("questionTypeId", record.id)
          updateForm.setFieldValue("questionName", record.questionName)
          updateForm.setFieldValue("questionScore", record.questionScore)
          handleUpdateModalOpen(true)
        }
        }>
          编辑
        </Button>,
        <Button type="primary" danger key={"delete"} onClick={async () => {
          const success = await handleDelete(record.id)
          if (success) {
            initData()
          }
        }
        }>
          删除
        </Button>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        columns={columns}
        dataSource={data}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}
      <ModalForm
        title={'新建题型'}
        width="400px"
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        // layout={"horizontal"} // 水平布局
        onFinish={async (value) => {
          const success = await handleAdd(value as API.QuestionTypeAddParams);
          if (success) {
            handleModalOpen(false);
            // 重新加载数据
            initData()
          }
        }}
      >
        <ProFormText
          name="questionName"
          label="题型名称"
          tooltip="最长为 8 位"
          placeholder="请输入题型名称"
          rules={[
            {
              required: true,
              message: '题型名称为必填项',
            },
          ]}
        />
        <ProFormDigit
          label="题型分数"
          name="questionScore"
          width="sm"
          min={1}
          max={100}
          rules={[
            {
              required: true,
              message: '题型名称为必填项',
            },
          ]}
        />
      </ModalForm>
      <ModalForm
        title={'修改题型'}
        width="400px"
        open={updateModalOpen}
        form={updateForm}
        onOpenChange={handleUpdateModalOpen}
        // layout={"horizontal"} // 水平布局
        onFinish={async (value) => {
          const success = await handleUpdate(value as API.QuestionTypeUpdateParams);
          if (success) {
            handleUpdateModalOpen(false);
            // 重新加载数据
            initData()
          }
        }}
      >
        <ProFormText
          name="questionTypeId"
          hidden={true}
        />
        <ProFormText
          name="questionName"
          label="题型名称"
          tooltip="最长为 8 位"
          placeholder="请输入题型名称"
          rules={[
            {
              required: true,
              message: '题型名称为必填项',
            },
          ]}
        />
        <ProFormDigit
          label="题型分数"
          name="questionScore"
          width="sm"
          min={1}
          max={100}
          rules={[
            {
              required: true,
              message: '题型名称为必填项',
            },
          ]}
        />
      </ModalForm>

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};
export default QuestionTypeTableList;
